package com.ylz.sjzx.sio.common.core.context;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Desc :
 * Date : 2019/6/4
 */
@Slf4j
@Component
public class ApplicationUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private static Environment environment;

    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }

    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    public static <T> Set<T> getBeans(Class<T> clazz) {
        Map<String, T> beanMap = applicationContext.getBeansOfType(clazz);
        return new HashSet<>(beanMap.values());
    }

    public static String getProperty(String key) {
        return environment.getProperty(key);
    }

    public static String getProperty(String key, String defaultKey) {
        String property = environment.getProperty(key);
        return property != null ? property : defaultKey;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext temp) throws BeansException {
        applicationContext = temp;
    }

    /**
     * 注册bin
     *
     * @param beanClass
     * @param <T>
     * @return
     */
    public static <T> boolean registerBean(Class<T> beanClass) {
        applicationContext.getAutowireCapableBeanFactory().createBean(beanClass);
        return true;
    }

    public static <T> boolean registerBean(String beanName, T bean) {
        // 将applicationContext转换为ConfigurableApplicationContext
        ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
        // 将bean对象注册到bean工厂
        context.getBeanFactory().registerSingleton(beanName, bean);
        log.info("【SpringContextUtil】注册实例“" + beanName + "”到spring容器：" + bean);
        return true;
    }

    @Autowired
    public void setEnvironment(Environment env) {
        environment = env;
    }
}
